/**************************************

    author  : xy_god
    e-mail  : xy_god@thesct.net
    homepage: http://www.thesct.net

    FileName: xbase.c
    gen_time: 2015.01.12

    comments:
        该文件实现了xbase库的初始化和一
    些全局变量的定义.

 **************************************/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "xbase.h"

//-------------------------------- start --------------------------------

// 获取保护堆栈的互斥对象
int* is_initialized()
{
  static b_initialized = 0;
  return &b_initialized;
}

pthread_mutex_t* get_mutex_malloc()
{
  static pthread_mutex_t h_mutex_malloc;
  return &h_mutex_malloc;
}

int xbase_is_initialized()
{
  return (*is_initialized());
}

int xbase_init()
{

  int i_err = 0;
  int i_ret = 0;
  int * pb_initialized = is_initialized();
  
  if ((*pb_initialized) != 0) {
	i_err = ERR_XB_REINIT;
	goto error_tray;
  }
  i_ret = pthread_mutex_init(get_mutex_malloc(), NULL);
  if(i_ret != 0) {
	i_err = i_ret;
	goto error_tray;
  }

  (*pb_initialized) = 1;
  return 0;
  
 error_tray: // 错误处理
  fprintf(stderr,                        // 错误输出
		  "xbase_init 中发生错误,错误号: [ %d ].", i_err);
  return i_err;
}

int xbase_uninit()
{

  int i_err = 0;
  int i_ret = 0;
  int * pb_initialized = is_initialized();
  
  if ((*pb_initialized) == 0) {
	i_err = ERR_XB_REUNINIT;
	goto error_tray;
  }
  i_ret = pthread_mutex_destroy(get_mutex_malloc());
  if(i_ret != 0) {
	i_err = i_ret;
	goto error_tray;
  }

  (*pb_initialized) = 0;
  return 0;
  
 error_tray: // 错误处理
  fprintf(stderr,                        // 错误输出
		  "xbase_uninit 中发生错误,错误号: [ %d ].", i_err);
  return i_err;
}

void * mallocs(size_t size)
{
  int i_ret = 0;
  int i_err = 0;
  void *ptr = NULL;
  i_ret = pthread_mutex_lock(get_mutex_malloc());
  if(i_ret != 0) {
	i_err = i_ret;
	goto error_tray;
  }
  ptr = malloc(size);
  i_ret = pthread_mutex_unlock(get_mutex_malloc());
  if(i_ret != 0) {
	i_err = i_ret;
	goto error_tray;
  }
  return ptr;
  
 error_tray: // 错误处理
  fprintf(stderr,                        // 错误输出
		  "mallocs 中发生错误,错误号: [ %d ].", i_err);
  return NULL;
}
void frees(void *ptr)
{
  int i_ret = 0;
  int i_err = 0;

  i_ret = pthread_mutex_lock(get_mutex_malloc());
  if(i_ret != 0) {
	i_err = i_ret;
	goto error_tray;
  }
  free(ptr);
  i_ret = pthread_mutex_unlock(get_mutex_malloc());
  if(i_ret != 0) {
	i_err = i_ret;
	goto error_tray;
  }
  return;
  
 error_tray: // 错误处理
  fprintf(stderr,                        // 错误输出
		  "frees 中发生错误,错误号: [ %d ].", i_err);
  return;
}

//--------------------------------  end  --------------------------------
